﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DlrBasic.Runtime
{
    /// <summary>
    /// Type conversion utility class.
    /// </summary>
    static class DlrBasicConvert
    {
        internal static Type IntType = typeof(short);
        internal static Type SingleType = typeof(float);
        internal static Type DoubleType = typeof(double);
        internal static Type StringType = typeof(string);
        internal static Type ValueType = typeof(ValueType);

        internal static int? ConversionScore(Type fromType, Type toType)
        {
            if (fromType == toType)
                return 0;

            if (fromType.IsValueType && toType.IsValueType)
            {
                if (toType == DoubleType)
                {
                    if (fromType == DoubleType)
                    {
                        return 0;
                    }
                    else if (fromType == SingleType)
                    {
                        return 1;
                    }
                    else if (fromType == IntType)
                    {
                        return 2;
                    }
                }
                else if (toType == SingleType)
                {
                    if (fromType == DoubleType)
                    {
                        return 4;
                    }
                    else if(fromType == SingleType)
                    {
                        return 0;
                    }
                    else if (fromType == IntType)
                    {
                        return 1;
                    }
                }
                else if (toType == IntType)
                {
                    if (fromType == DoubleType)
                    {
                        return 5;
                    }
                    else if (fromType == SingleType)
                    {
                        return 4;
                    }
                    else if (fromType == IntType)
                    {
                        return 0;
                    }
                }
            }
            
            return null;
        }

        internal static object Convert(object value, Type toType)
        {
            return global::System.Convert.ChangeType(value, toType);
        }
    }
}
